package Blog

import (
	"FromNowOnPromote/博客系统/Tblog/controllers"
	"FromNowOnPromote/博客系统/Tblog/models"
	"FromNowOnPromote/博客系统/Tblog/models/Blog"
	"FromNowOnPromote/博客系统/Tblog/models/User"
	"FromNowOnPromote/博客系统/Tblog/redis"
	"encoding/json"
	"strconv"
)

//查看博客文章
type ReadBlog struct {
	controllers.MainController
}

//构造响应数据
type ReadData struct {
	BlogId      int    //文章id
	BlogContent string //文章内容
	//BlogStatus int    //草稿
	BlogTitle     string //文章标题
	BlogView      int    //阅读数量
	EnableComment int    //是否允许评论
	IsDeleted     int    //删除状态
	UId           int    //文章的用户id
	UserName      string //用户名字
	IconUrl       string //用户头像
	Paper         int    //文章数量
	Fans          int64  //粉丝数
	Category      string //文章类别
	EditType      string //编辑类型
	CreateTime    string //创作时间
}

type CountPage struct {
	Id int
}

func (this *ReadBlog) Get() {
	blogid := this.Ctx.Input.Param(":blogid")
	//查库
	db := models.ConnDb()
	defer db.Close()
	var tb Blog.TBloginfo
	err1 := db.Where("blog_id = ?", blogid).Find(&tb).Error
	if err1 != nil {
		body := map[string]interface{}{"code": 300, "msg": "异常请求"}
		this.Data["json"] = body
		this.ServeJSON()
		return
	}
	//获取用户名
	var tbuser User.TbUser
	err2 := db.Where("uuid = ?", tb.UId).Find(&tbuser).Error
	if err2 != nil {
		body := map[string]interface{}{"code": 301, "msg": "异常请求"}
		this.Data["json"] = body
		this.ServeJSON()
		return
	}
	//阅读数量+1
	err3 := db.Model(tb).Where("blog_id = ?", blogid).Update(map[string]interface{}{"blog_view": tb.BlogView + 1}).Error
	if err3 != nil {
		body := map[string]interface{}{"code": 302, "msg": "异常请求"}
		this.Data["json"] = body
		this.ServeJSON()
		return
	}
	var c CountPage
	err4 := db.Raw("select count(blog_id) as id from tbloginfo where uid = ?;", tbuser.Uuid).Scan(&c).Error
	if err4 != nil {
		body := map[string]interface{}{"code": 303, "msg": "服务器异常"}
		this.Data["json"] = body
		this.ServeJSON()
		return
	}
	var readdata ReadData
	readdata.UserName = tbuser.Username
	readdata.IconUrl = tbuser.IconUrl
	readdata.Paper = c.Id
	b, err5 := json.Marshal(&tb)
	if err5 != nil {
		body := map[string]interface{}{"code": 304, "msg": "服务器异常"}
		this.Data["json"] = body
		this.ServeJSON()
		return
	}
	err6 := json.Unmarshal(b, &readdata)
	if err6 != nil {
		body := map[string]interface{}{"code": 305, "msg": "服务器异常"}
		this.Data["json"] = body
		this.ServeJSON()
		return
	}
	fans := redis.R.FansConn
	defer fans.Close()
	uid := strconv.Itoa(tb.UId)
	f, _ := fans.HLen(uid)
	readdata.Fans = f
	body := map[string]interface{}{"code": 200, "data": readdata}
	this.Data["json"] = body
	defer this.ServeJSON()
}
